﻿using System;

namespace LeakView.common
{
    public class Expirable<T>
    {
        private T value;
        public T Value { get => value; }

        private DateTime lastUpdate = DateTime.MinValue;
        public DateTime LastUpdate { get => lastUpdate; }

        private TimeSpan expire = TimeSpan.MaxValue;
        public TimeSpan Expire { get => expire; set => expire = value; }

        public bool Valid { get => isValid(this.expire); }

        public Expirable(T value, TimeSpan expire)
        {
            this.value = value;
            this.expire = expire;
        }

        public Expirable(T value)
        {
            this.value = value;
        }

        public Expirable(TimeSpan expire)
        {
            this.expire = expire;
        }

        public Expirable()
        {
        }

        public Expirable<T> clone()
        {
            Expirable<T> v = new Expirable<T>();
            v.expire = this.expire;
            v.value = this.value;
            v.lastUpdate = this.lastUpdate;
            return v;
        }

        public void update(T value)
        {
            this.value = value;
            this.lastUpdate = DateTime.Now;
        }

        public bool isValid(TimeSpan expire)
        {
            return value != null && expire > (DateTime.Now - lastUpdate);
        }

    }
}
